package com.quanyan.place.wrapper.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.quanyan.api.APIResponse;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.messagepush.entity.*;
import com.quanyan.messagepush.enums.BoxName;
import com.quanyan.messagepush.enums.BoxType;
import com.quanyan.messagepush.enums.IdType;
import com.quanyan.messagepush.enums.MsgType;
import com.quanyan.place.entity.PlaceMessage;
import com.quanyan.place.entity.TbBizPlace;
import com.quanyan.place.entity.vo.MqPlaceGroupId;
import com.quanyan.place.entity.vo.TbBizPlaceVo;
import com.quanyan.place.mapper.FinanceCommonManagerMapper;
import com.quanyan.place.service.PlaceInnerService;
import com.quanyan.place.service.PlaceTicketService;
import com.quanyan.place.wrapper.MqPlaceConsumerWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Kingson.chan on 2016/8/16 0016.
 */
@Service("mqPlaceConsumerWrapperImpl")
public class MqPlaceConsumerWrapperImpl implements MqPlaceConsumerWrapper {
    private static final Logger log = LoggerFactory.getLogger(MqPlaceConsumerWrapperImpl.class);

    @Autowired
    PlaceInnerService placeInnerService;

    @Autowired
    PlaceTicketService placeTicketService;
    @Value("${c.service.url}")
    public String cAddress;

    @Override
    public APIResponse placeConsumerOperate(MessageExt messageExt) {
        String msgId = messageExt.getMsgId();
        byte[] bodyByte = messageExt.getBody();
        if(MqPlaceConsumerWrapper.MQ_PLACE_GROUP_TYPE.equals(messageExt.getFlag())){
            MqPlaceGroupId mqPlaceGroupId = (MqPlaceGroupId) ObjectUtil.toObject(bodyByte);
            int result = placeInnerService.updatePlaceGroupId(mqPlaceGroupId);
            if(result > 0){
                log.info("mq消息：更新场馆群号成功，msgId:{}，场馆id:{}",msgId,mqPlaceGroupId.getId());
                APIResponse  apiResponse =  placeInnerService.getPlaceData(mqPlaceGroupId.getId());
                TbBizPlace tbBizPlace = (TbBizPlace)apiResponse.getData();
                TbBizPlaceVo tbBizPlaceVo = new TbBizPlaceVo();
                tbBizPlaceVo.setTbBizPlace(tbBizPlace);
                boolean flag = updatePlaceIndex(tbBizPlaceVo);
                if(flag){
                    log.info("mq消息：更新场馆索引成功，msgId:{}，场馆id:{}", msgId, tbBizPlaceVo.getTbBizPlace().getId());
                    return APIResponse.returnSuccess();
                }
                else {
                    log.info("mq消息：更新场馆索引失败，msgId:{}，场馆id:{}",msgId,tbBizPlaceVo.getTbBizPlace().getId());
                }
                return APIResponse.returnFail("");
            }
            else {
                log.info("mq消息：更新场馆群号失败，msgId:{}，场馆id:{}",msgId,mqPlaceGroupId.getId());
                return APIResponse.returnFail("");
            }
        }
        else if(MqPlaceConsumerWrapper.MQ_PLACE_PUSH_MESSAGE_TYPE.equals(messageExt.getFlag())){
            PlaceMessage placeMessage = (PlaceMessage) ObjectUtil.toObject(bodyByte);
            boolean flag = pushMessageOperate(placeMessage);
            if(flag){
                log.info("mq消息：消息推送成功，msgId:{}，订单号:{}",msgId,placeMessage.getOrderNo());
                return APIResponse.returnSuccess();
            }
            else {
                log.info("mq消息：消息推送失败，msgId:{}，订单号:{}",msgId,placeMessage.getOrderNo());
                return APIResponse.returnFail("");
            }
        }
        else if(MqPlaceConsumerWrapper.MQ_PLACE_UPDATE_INDEX_TYPE.equals(messageExt.getFlag())){
            TbBizPlaceVo tbBizPlaceVo = (TbBizPlaceVo) ObjectUtil.toObject(bodyByte);
            boolean flag = updatePlaceIndex(tbBizPlaceVo);
            if(flag){
                log.info("mq消息：更新场馆索引成功，msgId:{}，场馆id:{}", msgId, tbBizPlaceVo.getTbBizPlace().getId());
                return APIResponse.returnSuccess();
            }
            else {
                log.info("mq消息：更新场馆索引失败，msgId:{}，场馆id:{}",msgId,tbBizPlaceVo.getTbBizPlace().getId());
                return APIResponse.returnFail("");
            }

        }
        return APIResponse.returnSuccess();
    }

    private boolean pushMessageOperate(PlaceMessage placeMessage) {
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.ORDER.value() + System.currentTimeMillis());
        pushMessage.setTo(placeMessage.getUids());                          //下单用户的uid
        pushMessage.setLogo(Constants.LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        String body = "";
        String title = "";
        NewBody newBody = null;
        if(placeMessage.getOrderType() == 1){
            title = "场地预订提醒";
            body = "您已成功预订" + placeMessage.getDate() + placeMessage.getPlaceName() + "的" +placeMessage.getCategoryValue()+ "场地。";
        }
        else if(placeMessage.getOrderType() == 2){
            //title = "尊敬的" +placeMessage.getName()+"，您于" +placeMessage.getCurrTime() + "申请"+ placeMessage.getPlaceName() + "退订业务已成功，退款将于三个工作日内返还。有疑问请致电" + placeMessage.getServicePhone();
            title = "场地退款提醒";
            newBody = getNewBody(placeMessage);
            payload.setNewBody(newBody);
        }
        else if(placeMessage.getOrderType() == 3){
            String payType = "";
            if(placeMessage.getPayType() == 1){
                payType = "支付宝";

            }
            else if(placeMessage.getPayType() == 2 || placeMessage.getPayType() == 3){
                payType = "微信";
            }
            body="很抱歉，您的订单支付异常，系统将在2个工作日内退回已支付款项，具体到账时间以" +payType + "处理为准。如有需要，可重新下单。";
        }
        if(placeMessage.getOrderType() == 4){
            title = "场地门票购买提醒";
            int count = placeTicketService.getTicketSaleCountByOrderNo(placeMessage.getOrderNo());
            body = "您已成功购买" + placeMessage.getDate() + placeMessage.getPlaceName() + "的" +placeMessage.getCategoryValue()+ "门票"+ count +"张。";
        }
        if (placeMessage.getOrderType() == 2){//app端退款
            payload.setMsgType(MsgType.ORDER_MSG.value());//订单 5
        }else{
            payload.setMsgType(MsgType.JUMP_MSG.value());
        }

        Alert alert = new Alert();
        alert.setTitle("场馆订单");
        pushMessage.setAlert(alert);
        alert.setBody(title);
        payload.setTitle(title);
        payload.setTitle(body);
        payload.setBoxType(BoxType.PLACE_ORDER_MSG.value());
        payload.setUrl("/api/place/shops/orderDetail");
        Jump jump = new Jump();
        jump.setIdType(IdType.PLACE_ORDER_DETAIL_PAGE.value());
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("orderNo",placeMessage.getOrderNo());
        jump.setParam(param);
        payload.setJump(jump);

        payload.setTimestamp(System.currentTimeMillis());
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        try {
            String postJson = JSON.toJSONString(reqPushMessage);
            log.info("---------推送消息：" + postJson);
            String result = HttpClientUtils.postJson(cAddress + "/push/NewMsg.api", postJson);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String errcode = jsonObject.getString("errcode");
            log.info("---------推送返回：" + result);
            if(errcode != null && errcode.equals("200")){
                return true;
            }
        } catch (Exception e) {
            log.info("推送消息失败，" + e.getMessage());
        }
        return false;

    }
    @Autowired
    FinanceCommonManagerMapper financeCommonManagerMapper;
    private NewBody getNewBody(PlaceMessage placeMessage){
        NewBody newBody = new NewBody();
        newBody.setB("");
        newBody.setbColor("");

        Map<String, Object> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        list.add(placeMessage.getOrderNo());
        map.put("placeOrderId",list);
        BigDecimal payAmount = financeCommonManagerMapper.getOrderDiscountAmount(map);
        List<Entry> entries = new ArrayList<>();
        Entry entry = new Entry();
        entry.setKey("退款金额");
        entry.setValue(payAmount.toString()+"元");
        entry.setKcolor("#ed4d4d");
        entry.setVcolor("#ed4d4d");
        entries.add(entry);

        Entry entry1 = new Entry();
        entry1.setKey("场馆名称");
        entry1.setValue(placeMessage.getPlaceName());
        entry1.setKcolor("");
        entry1.setVcolor("");
        entries.add(entry1);

        Entry entry2 = new Entry();
        entry2.setKey("申请时间");
        entry2.setValue(DateUtils.transferLongToDateStrings(System.currentTimeMillis()));
        entry2.setKcolor("");
        entry2.setVcolor("");
        entries.add(entry2);

        Entry entry3 = new Entry();
        entry3.setKey("到账时间");
        entry3.setValue("三个工作日内");
        entry3.setKcolor("");
        entry3.setVcolor("");
        entries.add(entry3);

        newBody.setEntries(entries);
        return newBody;
    }
    private boolean updatePlaceIndex(TbBizPlaceVo tbBizPlaceVo){
        try {
            this.placeInnerService.addPlaceIndex(tbBizPlaceVo.getTbBizPlace(), tbBizPlaceVo.getIds());
            return true;
        } catch (Exception e) {
            log.error("增加索引失败：{}",e.getMessage());
        }
        return false;
    }


}
